package org.example.controller.user;

import jakarta.annotation.Resource;
import org.example.domain.Result;
import org.example.domain.iim.Relations;
import org.example.domain.user.Users;
import org.example.mapper.RelationsMapper;
import org.example.mapper.UsersMapper;
import org.example.utils.ThreadLocalUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
/**
 * @description: 管理员对用户的一些操作
 * @Author: whopxx
 * @CreateTime: 2025-01-05
 */
@RestController
@RequestMapping("/users")
public class AdminController {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RelationsMapper relationsMapper;

    @GetMapping("/list")
    public Result list() {
        return Result.success(usersMapper.selectList(null));
    }

    @PostMapping
    public Result add(@RequestBody Users users) {
        if(users.getUsername() == null || users.getUsername().isEmpty()){
            return Result.error("用户名不能为空");
        }
        if(users.getPassword() == null || users.getPassword().isEmpty()){
            return Result.error("密码不能为空");
        }
        Users user = usersMapper.findByUsername(users.getUsername());
        if(user != null){
            return Result.error("用户名已存在");
        }
        usersMapper.insert(users);
        return Result.success();
    }


    @PutMapping
    public Result update(@RequestBody Users users) {
        if(users.getUsername() == null || users.getUsername().isEmpty()){
            return Result.error("用户名不能为空");
        }
        if(users.getPassword() == null || users.getPassword().isEmpty()){
            users.setPassword(null);
        }
        usersMapper.updateById(users);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer nowId = (Integer) claims.get("id");
        if ( nowId.equals(id)){
            return Result.error("不能删除自己");
        }
        List<Relations> relations = relationsMapper.selectByUserId(id);
        if (!relations.isEmpty()){
            return Result.error("该用户有项目关联,不能删除");
        }
        usersMapper.deleteById(id);
        return Result.success();
    }
}
